package com.wen.system.mail.service.impl;

import com.wen.system.mail.pojo.MailRequest;
import com.wen.system.mail.service.SendMailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Service
public class SendMailServiceImpl implements SendMailService {
 
    // 注入邮件工具类
    @Resource
    private JavaMailSender javaMailSender;
 
    @Value("${spring.mail.username}")
    private String sendMailer;
 
    public void checkMail(MailRequest mailRequest) {
        Assert.isNull(mailRequest,"邮件请求不能为空");
        Assert.isNull(mailRequest.getSendTo(), "邮件收件人不能为空");
        Assert.isNull(mailRequest.getSubject(), "邮件主题不能为空");
        Assert.isNull(mailRequest.getText(), "邮件收件人不能为空");
    }
 
    @Override
    public void sendSimpleMail(MailRequest mailRequest) {
        SimpleMailMessage message = new SimpleMailMessage();
        checkMail(mailRequest);
        // 邮件发件人
        message.setFrom(sendMailer);
        // 邮件收件人 1或多个
        message.setTo(mailRequest.getSendTo().split(","));
        // 邮件主题
        message.setSubject(mailRequest.getSubject());
        // 邮件内容
        message.setText(mailRequest.getText());
        // 邮件发送时间
        message.setSentDate(new Date());
 
        javaMailSender.send(message);
        log.info("发送邮件成功:{}->{}",sendMailer,mailRequest.getSendTo());
    }
 
 
 
    @Override
    public void sendHtmlMail(MailRequest mailRequest) {
//        MimeMessage message = javaMailSender.createMimeMessage();
//        checkMail(mailRequest);
//        try {
//            MimeMessageHelper helper = new MimeMessageHelper(message,true);
//            //邮件发件人
//            helper.setFrom(sendMailer);
//            //邮件收件人 1或多个
//            helper.setTo(mailRequest.getSendTo().split(","));
//            //邮件主题
//            helper.setSubject(mailRequest.getSubject());
//            //邮件内容
//            helper.setText(mailRequest.getText(),true);
//            //邮件发送时间
//            helper.setSentDate(new Date());
//
//            String filePath = mailRequest.getFilePath();
//            if (StringUtils.hasText(filePath)) {
//                FileSystemResource file = new FileSystemResource(new File(filePath));
//                String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
//                helper.addAttachment(fileName,file);
//            }
//            javaMailSender.send(message);
//            log.info("发送邮件成功:{}->{}",sendMailer,mailRequest.getSendTo());
//        } catch (MessagingException e) {
//            log.error("发送邮件时发生异常！",e);
//        }
    }
}